import { ref } from "vue";

const loading =
  "http://caogen-media.oss-cn-hangzhou.aliyuncs.com/groupbuy/loading.gif";
interface OptionFace {
  /**
   * 共有几列
   */
  col?: number;
}
/**
 * 列表
 */
interface ListFace extends Record<string, any> {}
export function useWaterfall(option: OptionFace = {}) {
  const listHight = ref<number[]>([]);
  const lists = ref<any>([]);
  const { col = 2 } = option;
  // 初始化列数
  const initList = () => {
    listHight.value = new Array(col).fill(0) as number[];
    lists.value = new Array(col).fill(0).map((v) => []);
  };
  initList();

  //获取图片高度
  const getImgHeight = (url: string): Promise<number> => {
    return new Promise((resolve, reject) => {
      console.log(url);

      if (!url) return reject();
      uni.getImageInfo({
        src: url,
        success: function (image) {
          console.log(image.width);
          console.log(image.height);
          let h = image.height / image.width;
          resolve(h);
        },
        fail: () => {
          console.log("什么鬼");

          reject("error");
        },
      });
    });
  };
  const updateLoading = (
    item: string | ListFace,
    key: string,
    col: number,
    index: number,
    val = "http://caogen-media.oss-cn-hangzhou.aliyuncs.com/groupbuy/loading.gif"
  ) => {
    if (typeof item === "string") {
      lists.value[col][index] = val;
    } else {
      lists.value[col][index] = {
        ...item,
        [key]: val,
      };
    }
  };
  /**
   * 添加内容
   * @param list 列表 图片列表或者对象列表
   * @param key 如果是对象则传图片在对象内的key
   * @param isLoading 是否需要放入loading图片
   */
  const addList = async (
    list: string[] | ListFace[],
    key = "url",
    isLoading = true
  ) => {
    for (let item of list) {
      let url: string;
      if (typeof item === "string") {
        url = item;
      } else {
        url = item[key];
      }

      let minValue = Math.min(...listHight.value);
      let minIndex = listHight.value.indexOf(minValue);
      console.log(minIndex);
      const index = lists.value[minIndex].length;
      if (isLoading) {
        updateLoading(item, key, minIndex, index);
      }
      try {
        let h = await getImgHeight(url).catch(() => {
          if (isLoading) {
            lists.value[minIndex].pop();
          }
        }); //图片渲染后高度
        if (!h) continue;

        listHight.value[minIndex] += h;
        if (isLoading) {
          updateLoading(item, key, minIndex, index, url);
        } else {
          lists.value[minIndex].push(item);
        }
      } catch (e) {
        console.log(e);
      }
    }
  };
  return {
    lists,
    addList,
    initList,
  };
}
